package com.aiyige.page.publish.normalvideo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.db.DBHelper;
import com.aiyige.base.db.dao.NormalVideoModelDao;
import com.aiyige.base.db.dao.UploadFileDao;
import com.aiyige.base.db.table.NormalVideoModel;
import com.aiyige.base.db.table.UploadFile;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.page.my.settings.ConfigUltis;
import com.aiyige.page.publish.adapter.FormTagAdapter;
import com.aiyige.page.publish.inputintroduction.InputIntrodutionPage;
import com.aiyige.page.publish.inputtitle.SingleLineInputPage;
import com.aiyige.page.publish.normalvideo.model.PublishNormalVideoFormModel;
import com.aiyige.page.publish.normalvideo.model.PublishNormalVideoItem;
import com.aiyige.page.publish.photo.PublishPhotoPage;
import com.aiyige.page.publish.selectinterest.PublishSelectInterestPage;
import com.aiyige.page.publish.selectinterest.model.PublishIndustryItem;
import com.aiyige.page.publish.selectinterest.model.PublishInterestItem;
import com.aiyige.page.publish.selecttag.SelectTagPage;
import com.aiyige.page.publish.selecttag.model.SelectTagItem;
import com.aiyige.page.publish.util.PublishUtil;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.track.TrackEvent;
import com.aiyige.track.TrackUtil;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.CancelEditDialogUtil;
import com.aiyige.utils.FileUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.UUIDUtil;
import com.aiyige.utils.dialog.LoadingDialog;
import com.aiyige.utils.widget.CommonBottomDialogFragment;
import com.aiyige.utils.widget.GprsNotificationDialogUtil;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.j256.ormlite.misc.TransactionManager;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.vondear.rxtools.RxNetTool;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Track("发布视频")
@Route(path = ARouterConfig.PublishNormalVideoFormPage)
public class PublishNormalVideoFormPage extends BaseActivity {
    public static final String TAG = PublishNormalVideoFormPage.class.getSimpleName();
    public static final int REQUEST_CODE_INPUT_TITLE = 1;
    public static final int REQUEST_CODE_SELECT_COVRE = 2;
    public static final int REQUEST_CODE_SELECT_INTEREST = 5;
    public static final int REQUEST_CODE_SELECT_TAG = 9;
    public static final int REQUEST_CODE_INPUT_COURSE_INTRODUCTION = 10;

    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.coverIv)
    ImageView coverIv;
    @BindView(R.id.interestTv)
    TextView interestTv;
    @BindView(R.id.tagTv)
    TextView tagTv;
    @BindView(R.id.courseIntroductionTv)
    TextView courseIntroductionTv;
    @BindView(R.id.splitVideoTv)
    TextView splitVideoTv;
    @BindView(R.id.locationTv)
    TextView locationTv;
    @BindView(R.id.tagRv)
    RecyclerView tagRv;
    @Autowired
    PublishNormalVideoFormModel formModel;
    BroadcastReceiver broadcastReceiver;
    LocationData locationData = new LocationData();
    FormTagAdapter formTagAdapter;
    TrackEvent trackEvent = new TrackEvent();
    String mediaSource = TrackUtil.MEDIA_SOURCE_DEFAULT;
    CommonBottomDialogFragment locationOptionDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_publish_normal_video_form);
        ButterKnife.bind(this);
        formTagAdapter = new FormTagAdapter();
        tagRv.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        formTagAdapter.bindToRecyclerView(tagRv);
        formTagAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                switch (view.getId()) {
                    case R.id.deleteBtn:
                        formTagAdapter.remove(position);
                        if (formTagAdapter.getData().isEmpty()) {
                            tagRv.setVisibility(View.INVISIBLE);
                            tagTv.setVisibility(View.VISIBLE);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        parseIntent(getIntent());
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                try {
                    String action = intent.getAction();
                    switch (action) {
                        case LocationService.ACTION_LOCATION_FINISH: {
                            locationData = LocationService.obtainLocationData(intent);
                            if (locationData.isSuccess()) {
                                locationTv.setText(locationData.getCity());
                            } else {
                                locationTv.setText(R.string.click_retry);
                                LocationUtil.showLocationFailedDialog(PublishNormalVideoFormPage.this);
                            }
                            break;
                        }
                        default:
                            break;
                    }
                } catch (Exception e) {
                    Log.e(TAG, "onReceive:" + Log.getStackTraceString(e));
                }
            }
        };
        registerReceiver(broadcastReceiver, intentFilter);
        LocationService.startLocation(this);
        locationOptionDialog = CommonBottomDialogFragment.newBuilder()
                .layoutResId(R.layout.location_option_dialog)
                .viewIdList(Arrays.asList(R.id.deleteLocationBtn, R.id.relocationBtn, R.id.cancelBtn))
                .listener(new CommonBottomDialogFragment.Listener() {
                    @Override
                    public void onViewClicked(int position, View view) {
                        switch (view.getId()) {
                            case R.id.deleteLocationBtn:
                                locationData = new LocationData();
                                locationTv.setText(R.string.address_label);
                                break;
                            case R.id.relocationBtn:
                                LocationService.startLocation(PublishNormalVideoFormPage.this, true);
                                break;
                            case R.id.cancelBtn:
                                break;
                        }
                    }
                })
                .build();
    }

    public boolean checkFormValidate() {
//        if (!locationData.isSuccess()) {
//            ToastX.show(R.string.location_unfinished);
//            LocationService.startLocation(this);
//            return false;
//        }
//        if (ListUtil.isEmpty(formModel.getSelectTagItemList())) {
//            ToastX.show(R.string.please_select_tag);
//            return false;
//        }
        if (TextUtils.isEmpty(formModel.getTitle())) {
            ToastX.show(R.string.title_can_not_empty);
            return false;
        }

        if (TextUtils.isEmpty(formModel.getCoverUrl())) {
            ToastX.show(R.string.cover_can_not_empty);
            return false;
        }
//        if (TextUtils.isEmpty(formModel.getPublishInterestItem().getId())) {
//            ToastX.show(R.string.interest_can_not_empty);
//            return false;
//        }

        return true;
    }

    @Override
    protected void onDestroy() {
        try {
            unregisterReceiver(broadcastReceiver);
        } catch (Exception e) {

        }
        super.onDestroy();
    }

    public void parseIntent(Intent intent) {
        formModel = intent.getParcelableExtra("formModel");
        if (formModel == null) {
            formModel = PublishNormalVideoFormModel.newBuilder().build();
        }
        updateView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        parseIntent(intent);
    }

    public void updateView() {
//        formTagAdapter.setNewData(formModel.getSelectTagItemList());
        if (formTagAdapter.getData().isEmpty()) {
            tagRv.setVisibility(View.INVISIBLE);
            tagTv.setVisibility(View.VISIBLE);
        } else {
            tagRv.setVisibility(View.VISIBLE);
            tagTv.setVisibility(View.INVISIBLE);
        }
        titleTv.setText(formModel.getTitle());
//        interestTv.setText(formModel.getPublishInterestItem().getTitle());
        courseIntroductionTv.setText(formModel.getCourseIntroduction());
        splitVideoTv.setText(String.format(getString(R.string.have_selected_videos_num), formModel.getPublishNormalVideoItemList().size()));

        if (TextUtils.isEmpty(formModel.getCoverUrl())) {
            coverIv.setVisibility(View.INVISIBLE);
        } else {
            coverIv.setVisibility(View.VISIBLE);
            Glide.with(this)
                    .load(formModel.getCoverUrl())
                    .apply(RequestOptions.placeholderOf(R.drawable.default_image_bg))
                    .into(coverIv);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_INPUT_TITLE: {
                if (resultCode == RESULT_OK) {
                    formModel.setTitle(data.getStringExtra(SingleLineInputPage.EXTRA_KEY_INPUT_STRING));
                }
                break;
            }
            case REQUEST_CODE_SELECT_COVRE: {
                if (resultCode == RESULT_OK) {
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    if (!ListUtil.isEmpty(selectList)) {
                        formModel.setCoverUrl(selectList.get(0).getPath());
                    }
                    mediaSource = TrackUtil.detectMediaSource(formModel.getCoverUrl());
                }
                break;
            }
            case REQUEST_CODE_SELECT_INTEREST: {
                if (resultCode == RESULT_OK) {
//                    formModel.setPublishInterestItem(
//                            PublishInterestItem.newBuilder()
//                                    .id(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_ID))
//                                    .title(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_TITLE))
//                                    .parent(PublishIndustryItem.newBuilder()
//                                            .id(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_PARENT_ID))
//                                            .title(data.getStringExtra(PublishSelectInterestPage.EXTRA_KEY_SELECTED_PARENT_TITLE))
//                                            .build())
//                                    .build());
                }
                break;
            }

            case REQUEST_CODE_SELECT_TAG: {
                if (resultCode == RESULT_OK) {
                    trackEvent.sendEvent(this, TrackEvent.NORMAL_VIDEO_ADD_TAG, TrackEvent.NORMAL_VIDEO_ADD_TAG_LABEL, true);
//                    formModel.getSelectTagItemList().add(SelectTagItem.newBuilder()
//                            .id(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_ID))
//                            .name(data.getStringExtra(SelectTagPage.EXTRA_KEY_SELECTED_TAG_NAME))
//                            .build());
                }
                break;
            }
            case REQUEST_CODE_INPUT_COURSE_INTRODUCTION: {
                if (resultCode == RESULT_OK) {
                    formModel.setCourseIntroduction(data.getStringExtra(InputIntrodutionPage.EXTRA_KEY_INPUT_STRING));
                }
                break;
            }
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
        updateView();
    }

    @OnClick({R.id.titleBackBtn, R.id.titleLayout, R.id.coverLayout, R.id.interestLayout, R.id.tagLayout, R.id.courseIntroductionLayout, R.id.splitVideoLayout, R.id.submitBtn, R.id.locationLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.titleBackBtn:
                finish();
                break;
            case R.id.locationLayout:
//                locationTv.setText("");
//                LocationService.startLocation(this);
                locationOptionDialog.show(getSupportFragmentManager(), "");
                break;
            case R.id.titleLayout: {
                ARouter.getInstance()
                        .build(ARouterConfig.SingleLineInputPage)
                        .withString("pageTitle", getString(R.string.title))
                        .withString("action", getString(R.string.finish))
                        .withString("hint", getString(R.string.please_input_title))
                        .withInt("maxInputNum", 30)
                        .withString("text", formModel.getTitle())
                        .navigation(this, REQUEST_CODE_INPUT_TITLE);
                break;
            }
            case R.id.coverLayout: {
                List<LocalMedia> localMediaList = new LinkedList<>();
                List<PublishNormalVideoItem> publishLearnVideoItemList = formModel.getPublishNormalVideoItemList();
                for (PublishNormalVideoItem publishLearnVideoItem : publishLearnVideoItemList) {
                    LocalMedia localMedia = new LocalMedia();
                    localMedia.setPictureType("");
                    localMedia.setMimeType(PictureConfig.TYPE_IMAGE);
                    localMedia.setPath(publishLearnVideoItem.getCoverUrl());
                    localMediaList.add(localMedia);
                }
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .previewImage(false)
                        .isCamera(true)
                        .compress(false)
                        .enableCrop(false)
                        .isZoomAnim(false)
                        .previewEggs(false)
                        .selectionMode(PictureConfig.SINGLE)
                        .extraMedias(localMediaList)
                        .forResult(REQUEST_CODE_SELECT_COVRE);
                break;
            }

            case R.id.interestLayout: {
                ARouter.getInstance()
                        .build(ARouterConfig.PublishSelectInterestPage)
                        .navigation(this, REQUEST_CODE_SELECT_INTEREST);
                break;
            }
            case R.id.tagLayout: {
//                if (formModel.getSelectTagItemList().size() < PublishUtil.MAX_PUBLISH_TAG_NUM) {
//                    String[] selectedIds = new String[formTagAdapter.getData().size()];
//                    for (int i = 0; i < selectedIds.length; ++i) {
//                        selectedIds[i] = formTagAdapter.getData().get(i).getId();
//                    }
//                    ARouter.getInstance()
//                            .build(ARouterConfig.SelectTagPage)
//                            .withObject("selectedIds", selectedIds)
//                            .navigation(this, REQUEST_CODE_SELECT_TAG);
//                } else {
//                    ToastX.show(String.format(getString(R.string.reach_max_tag_select_num), PublishUtil.MAX_PUBLISH_TAG_NUM));
//                }
                break;
            }
            case R.id.courseIntroductionLayout: {
                ARouter.getInstance()
                        .build(ARouterConfig.InputIntroductionPage)
                        .withString("text", formModel.getCourseIntroduction())
                        .withString("title", StringUtils.getString(R.string.video_set_introduction))
                        .withInt("maxInputNum", 100)
                        .navigation(this, REQUEST_CODE_INPUT_COURSE_INTRODUCTION);
                break;
            }
            case R.id.splitVideoLayout: {
                trackEvent.sendEvent(this, TrackEvent.NORMAL_VIDEO_MOD_SPLIT_VIDEO, TrackEvent.NORMAL_VIDEO_MOD_SPLIT_VIDEO_LABEL, true);
                ARouter.getInstance()
                        .build(ARouterConfig.PublishNormalVideoPage)
                        .withParcelable("formModel", formModel)
                        .withBoolean("edit", true)
                        .navigation();
                break;
            }
            case R.id.submitBtn: {
                if (!checkFormValidate()) {
                    return;
                }
                doPublish();
                break;
            }
        }
    }

    private void doPublish() {
        if (!RxNetTool.isWifi(this) && ConfigUltis.isEnableGprsNotification()) {
            GprsNotificationDialogUtil.createPublishBuilder(this)
                    .setPositiveButton(R.string.confirm_upload, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            new AsyncTask<Object, Object, Object>() {
                                LoadingDialog loadingDialog;

                                @Override
                                protected void onPreExecute() {
                                    loadingDialog = LoadingDialog.newBuilder()
                                            .with(PublishNormalVideoFormPage.this)
                                            .message(R.string.text_process)
                                            .show();
                                }

                                @Override
                                protected Object doInBackground(Object... params) {
                                    try {
                                        return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                                            @Override
                                            public Object call() throws Exception {
                                                NormalVideoModel normalVideoModel = NormalVideoModel.newBuilder()
                                                        .id(UUIDUtil.generate())
                                                        .userId(AccountUtil.getCurrentUser().getId())
                                                        .releaseDate(System.currentTimeMillis())
                                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                        .introduction(formModel.getCourseIntroduction())
//                                                        .interestCategory(JSON.toJSONString(formModel.getPublishInterestItem()))
//                                                        .tag(JSON.toJSONString(formModel.getSelectTagItemList()))
                                                        .title(formModel.getTitle())
                                                        .location(JSON.toJSONString(locationData))
                                                        .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                                        .videoNum(formModel.getPublishNormalVideoItemList().size())
                                                        .build();
                                                UploadFile normalVideoCover = UploadFile.newBuilder()
                                                        .userId(AccountUtil.getCurrentUser().getId())
                                                        .fileLocalUrl(formModel.getCoverUrl())
                                                        .storeKey(PublishUtil.generatePhotoFileStoreKey(formModel.getCoverUrl()))
                                                        .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                                        .parentId(normalVideoModel.getId())
                                                        .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                                        .totalSize(FileUtil.getFileSize(formModel.getCoverUrl()))
                                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                        .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                                        .build();
                                                UploadFileDao.getDao().create(normalVideoCover);
                                                normalVideoModel.setCoverStoreKey(normalVideoCover.getStoreKey());
                                                normalVideoModel.setCoverUrl(normalVideoCover.getFileLocalUrl());
                                                NormalVideoModelDao.getDao().create(normalVideoModel);
                                                List<PublishNormalVideoItem> videoItemList = formModel.getPublishNormalVideoItemList();
                                                for (PublishNormalVideoItem videoItem : videoItemList) {
                                                    UploadFile videoCover = UploadFile.newBuilder()
                                                            .userId(AccountUtil.getCurrentUser().getId())
                                                            .fileLocalUrl(videoItem.getCoverUrl())
                                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                                            .storeKey(PublishUtil.generatePhotoFileStoreKey(videoItem.getCoverUrl()))
                                                            .parentId(normalVideoModel.getId())
                                                            .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                                            .totalSize(FileUtil.getFileSize(videoItem.getCoverUrl()))
                                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                                            .build();
                                                    UploadFileDao.getDao().create(videoCover);
                                                    UploadFile video = UploadFile.newBuilder()
                                                            .userId(AccountUtil.getCurrentUser().getId())
                                                            .fileLocalUrl(videoItem.getVideoUrl())
                                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_VIDEO)
                                                            .storeKey(PublishUtil.generateVideoFileStoreKey(videoItem.getVideoUrl()))
                                                            .parentId(normalVideoModel.getId())
                                                            .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                                            .totalSize(videoItem.getSize())
                                                            .duration(videoItem.getDuration())
                                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                                            .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                                            .title(videoItem.getTitle())
                                                            .coverStoreKey(videoCover.getStoreKey())
                                                            .coverUrl(videoCover.getFileLocalUrl())
                                                            .build();
                                                    UploadFileDao.getDao().create(video);
                                                }
                                                {
                                                    Map<String, String> attrs = new HashMap<>();
                                                    switch (mediaSource) {
                                                        case TrackUtil.MEDIA_SOURCE_ALBUM:
                                                            attrs.put("cover_type", "3");
                                                            break;
                                                        case TrackUtil.MEDIA_SOURCE_CAMERA_SHOT:
                                                            attrs.put("cover_type", "1");
                                                            break;
                                                        case TrackUtil.MEDIA_SOURCE_DEFAULT:
                                                            attrs.put("cover_type", "0");
                                                            break;
                                                        case TrackUtil.MEDIA_SOURCE_SUB_VIDEO_COVER:
                                                            attrs.put("cover_type", "2");
                                                            break;
                                                    }
                                                    trackEvent.sendEvent(PublishNormalVideoFormPage.this, TrackEvent.SELECT_NORMAL_VIDEO_COVER_TYPE, TrackEvent.SELECT_NORMAL_VIDEO_COVER_TYPE_LABEL, attrs);
                                                }
                                                return null;
                                            }
                                        });

                                    } catch (Exception e) {
                                        return e;
                                    }
                                }

                                @Override
                                protected void onPostExecute(Object o) {
                                    loadingDialog.dismiss();
                                    if (o instanceof Exception) {
                                        ToastX.show(((Exception) o).getMessage());
                                    } else {
                                        PublishUtil.startPublish();
                                        ToastX.show(R.string.publishing_normal_video_wait_a_second);
                                        PublishNormalVideoFormPage.super.finish();
                                        ARouter.getInstance()
                                                .build(ARouterConfig.UserPage)
                                                .withString("userId", AccountUtil.getCurrentUser().getId())
                                                .navigation();
                                    }
                                }
                            }.execute();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null)
                    .create()
                    .show();
        } else {
            new AsyncTask<Object, Object, Object>() {
                LoadingDialog loadingDialog;

                @Override
                protected void onPreExecute() {
                    loadingDialog = LoadingDialog.newBuilder()
                            .with(PublishNormalVideoFormPage.this)
                            .message(R.string.text_process)
                            .show();
                }

                @Override
                protected Object doInBackground(Object... params) {
                    try {
                        return TransactionManager.callInTransaction(DBHelper.getInstance().getConnectionSource(), new Callable<Object>() {
                            @Override
                            public Object call() throws Exception {
                                NormalVideoModel normalVideoModel = NormalVideoModel.newBuilder()
                                        .id(UUIDUtil.generate())
                                        .userId(AccountUtil.getCurrentUser().getId())
                                        .releaseDate(System.currentTimeMillis())
                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                        .introduction(formModel.getCourseIntroduction())
//                                        .interestCategory(JSON.toJSONString(formModel.getPublishInterestItem()))
//                                        .tag(JSON.toJSONString(formModel.getSelectTagItemList()))
                                        .title(formModel.getTitle())
                                        .location(JSON.toJSONString(locationData))
                                        .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                        .videoNum(formModel.getPublishNormalVideoItemList().size())
                                        .build();
                                UploadFile normalVideoCover = UploadFile.newBuilder()
                                        .userId(AccountUtil.getCurrentUser().getId())
                                        .fileLocalUrl(formModel.getCoverUrl())
                                        .storeKey(PublishUtil.generatePhotoFileStoreKey(formModel.getCoverUrl()))
                                        .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                        .parentId(normalVideoModel.getId())
                                        .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                        .totalSize(FileUtil.getFileSize(formModel.getCoverUrl()))
                                        .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                        .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                        .build();
                                UploadFileDao.getDao().create(normalVideoCover);
                                normalVideoModel.setCoverStoreKey(normalVideoCover.getStoreKey());
                                normalVideoModel.setCoverUrl(normalVideoCover.getFileLocalUrl());
                                NormalVideoModelDao.getDao().create(normalVideoModel);
                                List<PublishNormalVideoItem> videoItemList = formModel.getPublishNormalVideoItemList();
                                for (PublishNormalVideoItem videoItem : videoItemList) {
                                    UploadFile videoCover = UploadFile.newBuilder()
                                            .userId(AccountUtil.getCurrentUser().getId())
                                            .fileLocalUrl(videoItem.getCoverUrl())
                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_PHOTO)
                                            .storeKey(PublishUtil.generatePhotoFileStoreKey(videoItem.getCoverUrl()))
                                            .parentId(normalVideoModel.getId())
                                            .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                            .totalSize(FileUtil.getFileSize(videoItem.getCoverUrl()))
                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                            .progressStatus(PublishUtil.PROGRESS_STATUS_WAITING_UPLOAD)
                                            .build();
                                    UploadFileDao.getDao().create(videoCover);
                                    UploadFile video = UploadFile.newBuilder()
                                            .userId(AccountUtil.getCurrentUser().getId())
                                            .fileLocalUrl(videoItem.getVideoUrl())
                                            .fileType(PublishUtil.UPLOAD_FILE_TYPE_VIDEO)
                                            .storeKey(PublishUtil.generateVideoFileStoreKey(videoItem.getVideoUrl()))
                                            .parentId(normalVideoModel.getId())
                                            .parentType(PublishUtil.PARENT_TYPE_NORMAL_VIDEO)
                                            .totalSize(videoItem.getSize())
                                            .duration(videoItem.getDuration())
                                            .controlOption(PublishUtil.CONTROL_OPTION_UPLOAD)
                                            .progressStatus(PublishUtil.PROGRESS_STATUS_NEED_TRANSCODE)
                                            .title(videoItem.getTitle())
                                            .coverStoreKey(videoCover.getStoreKey())
                                            .coverUrl(videoCover.getFileLocalUrl())
                                            .build();
                                    UploadFileDao.getDao().create(video);
                                }
                                {
                                    Map<String, String> attrs = new HashMap<>();
                                    switch (mediaSource) {
                                        case TrackUtil.MEDIA_SOURCE_ALBUM:
                                            attrs.put("cover_type", "3");
                                            break;
                                        case TrackUtil.MEDIA_SOURCE_CAMERA_SHOT:
                                            attrs.put("cover_type", "1");
                                            break;
                                        case TrackUtil.MEDIA_SOURCE_DEFAULT:
                                            attrs.put("cover_type", "0");
                                            break;
                                        case TrackUtil.MEDIA_SOURCE_SUB_VIDEO_COVER:
                                            attrs.put("cover_type", "2");
                                            break;
                                    }
                                    trackEvent.sendEvent(PublishNormalVideoFormPage.this, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE, TrackEvent.SELECT_LEARN_VIDEO_COVER_TYPE_LABEL, attrs);
                                }
                                return null;
                            }
                        });

                    } catch (Exception e) {
                        return e;
                    }
                }

                @Override
                protected void onPostExecute(Object o) {
                    loadingDialog.dismiss();
                    if (o instanceof Exception) {
                        ToastX.show(((Exception) o).getMessage());
                    } else {
                        PublishUtil.startPublish();
                        ToastX.show(R.string.publishing_normal_video_wait_a_second);
                        PublishNormalVideoFormPage.super.finish();
                        ARouter.getInstance()
                                .build(ARouterConfig.UserPage)
                                .withString("userId", AccountUtil.getCurrentUser().getId())
                                .navigation();
                    }
                }
            }.execute();
        }
    }

    @Override
    public void finish() {
        CancelEditDialogUtil.newbuilder(this)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PublishNormalVideoFormPage.super.finish();
                        trackEvent.sendEvent(PublishNormalVideoFormPage.this, TrackEvent.CANCEL_PUBLISH_NORMAL_VIDEO, TrackEvent.CANCEL_PUBLISH_NORMAL_VIDEO_LABEL);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .create()
                .show();
    }
}
